package socket;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

public class EchoClient {

    private final String host;
    private final int post;

    public EchoClient(String host, int post) {
        this.host = host;
        this.post = post;
    }

    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            // 创建 引导
            Bootstrap b = new Bootstrap();

            // 指定EventLoopGroup处理客户端事件
            b.group(group)

                    // 适用于NIO传输的Channel类型
                    .channel(NioSocketChannel.class)

                    // 设置服务器的地址
                    .remoteAddress(new InetSocketAddress(host, post))

                    // 在创建Channel时向ChannelPipeline中添加一个实例
                    .handler(new ChannelInitializer<SocketChannel>() {

                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new EchoClientHandler());
                        }
                    });

            // 连接到远程节点，阻塞等待直到连接完成
            ChannelFuture f = b.connect().sync();

            // 阻塞，直到Channel关闭
            f.channel().closeFuture().sync();
        } finally {

            // 关闭线程池，并释放资源
            group.shutdownGracefully().sync();
        }

    }

    public static void main(String[] args) throws InterruptedException {
//        if (args.length != 2) {
//            System.err.println("Usage: " + EchoClient.class.getSimpleName() + "<host> <port>");
//            return;
//        }
//
//        String host = args[0];
//        int post = Integer.parseInt(args[1]);

        String host = "127.0.0.1";
        int post = 9999;
        new EchoClient(host, post).start();
    }

}
